import { PageContainer, ProTable } from "@ant-design/pro-components";
import { Button, Modal, Popconfirm, Space, Spin } from "antd";
import { connect } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useState, useRef } from "react";
import { message } from "antd";
import { history } from "umi";
import React from "react";
import Https from "@/utils/Https";
import { PlusOutlined } from "@ant-design/icons";

const Page = (props) => {
  const { dispatch } = props;
  const [qrcode, setQrcode] = useState(false);
  const actionRef = useRef();
  const [QRCodeUrl, setQRCodeUrl] = useState("");
  const [venueObj, setVenueObj] = useState({});
  const [qrError, setQrError] = useState("");
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
    });
  }, []);
  const toggleState = async (params) => {
    let res = await Https.post(
      "/venue/info/updateVenueStatus?id=" + params.id,
      {},
      true
    );
    if (res.code == 200) {
      message.success("操作成功");
      actionRef.current && actionRef.current.reload();
    } else {
      message.error(res.msg);
    }
  };

  const changeCanvasToPic = () => {
    const x = new XMLHttpRequest();
    x.open("GET", QRCodeUrl, true);
    x.responseType = "blob";
    x.onload = function () {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = venueObj.venueName + ".png";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
    x.send();
  };
  //获取小程序码
  const getQrcodeUlr = async (id) => {
    setLoading(true);
    setQrcode(true);
    setQrError("");
    let res = await Https.get("/venue/info/generateCodeUrl", { id }, true);
    if (res.code == 200) {
      setQRCodeUrl(res.data);
    } else {
      setQrError(res.msg);
      message.error(res.msg);
    }
    setLoading(false);
  };
  //删除场馆
  const deleteItem = async (id) => {
    let res = await Https.post("/venue/classroom/updateStatus", { id }, true);
    if (res.code == 200) {
      message.success("操作成功");
      actionRef.current && actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operate",
    hideInSearch: true,
    width: 300,
    align: "center",
    render: (_, record) => {
      const { venueStatus } = record;
      return (
        <Space>
          <Button
            type="link"
            onClick={() => {
              history.push(`/stadium/details/${record.id}`);
            }}
          >
            编辑
          </Button>
          {parseInt(venueStatus, 10) === 0 ? (
            <Button type="link" onClick={() => toggleState({ id: record.id })}>
              禁用
            </Button>
          ) : (
            <Button type="link" onClick={() => toggleState({ id: record.id })}>
              启用
            </Button>
          )}
          <Popconfirm
            title="确定要删除该场馆吗?"
            onConfirm={() => deleteItem(record.id)}
          >
            <Button type="link" disabled={record.venueStatus == 0} danger>
              删除
            </Button>
          </Popconfirm>
          <Button
            type="link"
            onClick={() => {
              getQrcodeUlr(record.id);
              setVenueObj(record);
            }}
          >
            小程序码
          </Button>
        </Space>
      );
    },
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              history.push("/stadium/details/0");
            }}
          >
            新增场馆
          </Button>,
        ]}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        scroll={{ x: 1000 }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({ operate })}
      />

      <Modal
        open={qrcode}
        title="小程序码"
        onCancel={() => {
          setQrcode(false);
          setQRCodeUrl("");
        }}
        footer={false}
      >
        <Spin spinning={loading}>
          <div style={{ minHeight: "150px" }}>
            {QRCodeUrl && (
              <>
                <div
                  style={{
                    width: "100%",
                    textAlign: "center",
                    marginBottom: "20px",
                  }}
                >
                  <img
                    id="qrCode"
                    style={{ width: "200px", height: "200px" }}
                    src={QRCodeUrl}
                  />
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    flexDirection: "column",
                  }}
                >
                  <Button
                    style={{
                      marginTop: "20px",
                    }}
                    type="primary"
                    onClick={changeCanvasToPic}
                  >
                    保存本地
                  </Button>
                </div>
              </>
            )}
            {qrError && (
              <>
                <div
                  style={{
                    width: "100%",
                    textAlign: "center",
                    marginBottom: "20px",
                  }}
                >
                  {qrError}
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    flexDirection: "column",
                  }}
                >
                  <Button
                    style={{
                      marginTop: "20px",
                    }}
                    type="primary"
                    onClick={() => {
                      getQrcodeUlr(venueObj.id);
                    }}
                  >
                    重新生成二维码
                  </Button>
                </div>
              </>
            )}
          </div>
        </Spin>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
